package com.wswy.wzcx.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.Space;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.che.libcommon.api.ApiOptionalResultObserver;
import com.che.libcommon.api.BaseResult;
import com.che.libcommon.ui.BaseActivity;
import com.che.libcommon.utils.ToastUtils;
import com.wswy.wzcx.R;
import com.wswy.wzcx.model.BillType;
import com.wswy.wzcx.model.DataCenter;
import com.wswy.wzcx.model.GenreChild;
import com.wswy.wzcx.statistics.StatTools;
import com.wswy.wzcx.statistics.StatisticsId;
import com.wswy.wzcx.ui.persenter.AddBillPresenter;
import com.wswy.wzcx.ui.persenter.AddBillPresenter.DateSetCallBack;
import com.wswy.wzcx.ui.view.AddBillView;
import com.wswy.wzcx.ui.other.AndroidUtilities;
import com.wswy.wzcx.ui.other.LayoutHelper;
import com.wswy.wzcx.ui.adapter.BaseAdapter;
import com.wswy.wzcx.ui.hold.ViewHolder;
import com.wswy.wzcx.widget.utils.MoneyTextWatcher;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


/**
 * Created by wangduheng26 on 2018/1/23.
 * wangduheng26@gmail.com
 */

public class AddBillActivity extends BaseActivity implements View.OnClickListener,AddBillView {

    private RecyclerView recyclerView;
    private EditText edAmount;
    private LinearLayout llBottom;

    private View back;
    private TextView tvTitle;
    private View llTimePicket;
    private TextView tvTime;
    private EditText edDesc;
    private AddBillPresenter presenter;
    private List<BillType> types;

    private GenreChild defaultChild;
    private Calendar chooseCalendar;
    private BillType currentType;

    public static Intent asIntent(Context context, GenreChild child) {
        Intent intent = new Intent(context, AddBillActivity.class);
        intent.putExtra("data", child);
        return intent;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_bill);

        recyclerView = findViewById(R.id.recycler_view);
        edAmount = findViewById(R.id.ed_amount);
        llBottom = findViewById(R.id.bottom);
        back = findViewById(R.id.img_back);
        tvTitle = findViewById(R.id.tv_title);
        llTimePicket = findViewById(R.id.ll_time_picket);
        tvTime =findViewById(R.id.tv_choose_time);
        edDesc = findViewById(R.id.ed_desc);


        presenter = new AddBillPresenter(this);
        tvTitle.setText(R.string.add_bill_title);
        initArgs();
        setup();
    }


    private void initArgs() {
        types = createMode();
        final Intent intent = getIntent();
        if (intent == null || intent.getExtras() == null) {
            chooseCalendar = Calendar.getInstance();
            currentType = types.get(0);
        } else {
            Bundle extras = intent.getExtras();
            defaultChild = extras.getParcelable("data");
            if (defaultChild != null) {
                try {
                    chooseCalendar=presenter.parseDate(defaultChild.expensesDate);
                    for (BillType type : types) {
                        if (TextUtils.equals(defaultChild.title, type.content)) {
                            currentType = type;
                        }
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    TextView tvAgain;
    TextView tvSave;
    TextView tvDelete;

    private void initView(TextView view, int textId, int backId) {
        if (view != null) {
            view.setGravity(Gravity.CENTER);
            view.setText(textId);
            view.setMinHeight(AndroidUtilities.dp(44));
            view.setBackgroundResource(backId);
            LayoutHelper.setSelectable(view);
        }
    }

    private void setup() {
        recyclerView.setLayoutManager(new GridLayoutManager(this, 5));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(new BaseAdapter<BillType, BillTypeVH>(types) {
            @Override
            public BillTypeVH onCreateViewHolder(LayoutInflater inflater, ViewGroup parent, int viewType) {
                final Context context = parent.getContext();
                TextView textView = new TextView(context);
                textView.setGravity(Gravity.CENTER);
                textView.setPadding(10, 20, 10, 20);
                textView.setCompoundDrawablePadding(AndroidUtilities.dp(6));
                textView.setTextColor(ContextCompat.getColor(context, R.color.bill_type_text));
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                return new BillTypeVH(textView);
            }

            @Override
            public void onBindViewHolder(BillTypeVH holder, BillType item, int position) {
                holder.bind(item);
                if (item == currentType) {
                    holder.itemView.setSelected(true);
                } else {
                    holder.itemView.setSelected(false);
                }
                holder.itemView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final Object tag = v.getTag();
                        if (tag instanceof BillType) {
                            currentType = (BillType) tag;
                            notifyDataSetChanged();
                        }
                    }
                });
            }
        });
        if (defaultChild != null) {
            tvDelete = new TextView(this);
            initView(tvDelete, R.string.delete, R.drawable.again_add_bg);
            llBottom.addView(tvDelete, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 2f));
            tvDelete.setOnClickListener(this);
        } else {
            tvAgain = new TextView(this);
            initView(tvAgain, R.string.again_add, R.drawable.again_add_bg);
            llBottom.addView(tvAgain, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1f));
            tvAgain.setOnClickListener(this);

        }
        Space space = new Space(this);
        llBottom.addView(space, LayoutHelper.createLinear(20, LayoutHelper.MATCH_PARENT));
        tvSave = new TextView(this);
        initView(tvSave, R.string.save, R.drawable.btn_save_bg);
        tvSave.setTextColor(Color.WHITE);
        tvSave.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        LinearLayout.LayoutParams linear = LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 2f);
        llBottom.addView(tvSave, linear);
        tvSave.setOnClickListener(this);
        llTimePicket.setOnClickListener(this);
        back.setOnClickListener(this);
        updateShowTime();
        if (defaultChild != null) {
            edDesc.setText(defaultChild.desc);
            edAmount.setText(defaultChild.content);
            if(!TextUtils.isEmpty(defaultChild.content)){
                edAmount.setSelection(defaultChild.content.length());
            }
        }
        edAmount.addTextChangedListener(new MoneyTextWatcher());
    }

    private List<BillType> createMode() {
        List<BillType> list = new ArrayList<>();
        String[] contents = DataCenter.get().contents;
        int[] icons = DataCenter.get().icons;
        for (int i = 0; i < DataCenter.TYPE_COUNT; i++) {
            list.add(new BillType(icons[i], contents[i]));
        }
        return list;
    }


    @Override
    public void onClick(View v) {
        if (v == tvAgain) {
            presenter.save(new ApiOptionalResultObserver<Object>() {
                @Override
                protected void onApiResult(@Nullable Object s) {
                    ToastUtils.showText("保存成功");
                    setResult(RESULT_OK);
                    edAmount.setText("");
                    currentType = null;
                    chooseCalendar = Calendar.getInstance();
                    tvTime.setText(R.string.now_day);
                    recyclerView.getAdapter().notifyDataSetChanged();
                }

                @Override
                protected void onApiError(@Nullable BaseResult result) {
                    toastErrorMsg(result);
                }
            }, currentType, edAmount,edDesc,presenter.format(chooseCalendar),-1);
            StatTools.sendClick(AddBillActivity.this, StatisticsId.clickAgainInBillPage);

        } else if (v == tvSave) {
            int id=defaultChild==null?-1:defaultChild.id;
            presenter.save(new ApiOptionalResultObserver<Object>() {
                @Override
                protected void onApiResult(@Nullable Object s) {
                    ToastUtils.showText("保存成功");
                    setResult(RESULT_OK);
                    finish();
                }

                @Override
                protected void onApiError(@Nullable BaseResult result) {
                    toastErrorMsg(result);
                }
            }, currentType, edAmount,edDesc,presenter.format(chooseCalendar),id);
            StatTools.sendClick(AddBillActivity.this, StatisticsId.clickSaveInBillPage);

        } else if (v == tvDelete) {
            presenter.delete(new ApiOptionalResultObserver<Object>() {
                @Override
                protected void onApiResult(@Nullable Object s) {
                    ToastUtils.showText("删除成功");
                    setResult(RESULT_OK);
                    finish();
                }

                @Override
                protected void onApiError(@Nullable BaseResult result) {
                    toastErrorMsg(result);
                }
            }, defaultChild);
        } else if (v == llTimePicket) {
            presenter.showDatePicker(new DateSetCallBack() {
                @Override
                public void callback(int year, int month, int dayOfMonth) {
                    chooseCalendar.set(Calendar.YEAR, year);
                    chooseCalendar.set(Calendar.MONTH, month);
                    chooseCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    updateShowTime();
                }
            });

        } else if (v == back) {
            finish();
        }
    }


    private void updateShowTime() {
        Calendar instance = Calendar.getInstance();
        instance.clear(Calendar.HOUR_OF_DAY);
        instance.clear(Calendar.MINUTE);
        instance.clear(Calendar.SECOND);
        instance.clear(Calendar.MILLISECOND);
        chooseCalendar.clear(Calendar.HOUR_OF_DAY);
        chooseCalendar.clear(Calendar.MINUTE);
        chooseCalendar.clear(Calendar.SECOND);
        chooseCalendar.clear(Calendar.MILLISECOND);

        if (instance.compareTo(chooseCalendar) == 0) {
            tvTime.setText(R.string.now_day);
        } else {
            tvTime.setText(presenter.format(chooseCalendar));
        }
    }

    @Override
    public Activity activity() {
        return this;
    }

    class BillTypeVH extends ViewHolder {

        public BillTypeVH(View itemView) {
            super(itemView);
        }

        public void bind(BillType item) {
            if (itemView instanceof TextView) {
                ((TextView) itemView).setText(item.content);
                ((TextView) itemView).setCompoundDrawablesWithIntrinsicBounds(0, item.icon, 0, 0);
            }
        }
    }
}
